<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { Search, Refresh, CirclePlus, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus'
import {
  reqFindCommunityList,
  reqAddCommunityNews,
  reqFindCommunityNewsById,
  reqModifyCommunityNews,
  reqRemoveCommunityNews,
  reqUploadPic
} from '@/api/message';
import { ResCommunityListItem, addCommunityNewsParams } from './type';
import { useStore } from '@/pinna';
const infoStore = useStore()
onMounted(() => {
  findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)
const searchFrom: Ref<{ title: string }> = ref({
  title: '',
})

const reset = () => {
  searchFrom.value = {
    title: '',
  }
  findData()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  findData()
}

const handleCurrentChange = (val: number) => {
  pageNo.value = val
  findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<ResCommunityListItem[]>> = ref([])

const findData = async () => {
  await reqFindCommunityList({
    pageNo: toValue(pageNo),
    pageSize: toValue(pageSize),
    title: toValue(searchFrom).title
  }).then((res: any) => {
    const { code, data, total: tableTotal } = res

    if (code === 200) {
      tableData.value = data
      total.value = tableTotal

    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

let editId = ref('')

const editRoleInfo = async (id: string) => {
  findRoleInfo(id, 'edit')
  editId.value = id
}

const findRoleInfo = async (id: string, type?: 'edit' | 'add') => {
  await reqFindCommunityNewsById({ id }).then((res: any) => {
    const { data } = res
    console.log(data);

    addHsotForm.value = data
    fileList.value = data.pic && data.pic.length > 0 ?
      (data.pic as string[]).map(t => {
        return {
          name: 'test.jpeg',
          url: t
        }
      }) : []

    dialogHostTitle.value = type === 'edit' ? '编辑社区资讯' : '查看社区资讯'
    dialogHost.value = true
  })
}

const deleteRoleInfo = async (id: string) => {
  ElMessageBox.confirm(
    '是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await reqRemoveCommunityNews({ id }).then((res: any) => {
        if (res.code == 200) {
          findData()
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
        }
      })
    })

}


// 添加社区资讯弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加社区资讯')
const formLabelWidth = '100px'
const addHsotForm: Ref<addCommunityNewsParams> = ref({
  title: '',
  content: '',
  author: '',
  views: 0,
  pic: []
})

const resetDialogHostFrom = () => {
  addHsotForm.value = {
    title: '',
    content: '',
    author: '',
    pic: []
  }
}

const addHostDialog = () => {
  resetDialogHostFrom()
  dialogHostTitle.value = '添加社区资讯'
  dialogHost.value = true
}
// 上传
let fileList = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const updataImg = async (data: any) => {
  await reqUploadPic({ image: data.file }).then((res: any) => {
    console.log(res);
    addHsotForm.value.pic?.push(res.data)
  })
}

const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  const index = addHsotForm.value.pic?.findIndex(t => t == uploadFile.url)
  toValue(addHsotForm).pic.splice(index, 1)

}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const addHostSubmit = async () => {
  if (dialogHostTitle.value == '添加社区资讯') {
    await reqAddCommunityNews(unref(addHsotForm)).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '新增社区资讯成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '编辑社区资讯') {
    await reqModifyCommunityNews({ ...unref(addHsotForm), id: unref(editId), publishTime: '' }).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '编辑资讯成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  }

}

const isReadonlyHandler = computed(() => {
  return dialogHostTitle.value !== '查看社区资讯'
})

</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span><strong>社区资讯管理</strong></span>
      </div>
    </template>
    <div class="query-input">
      <el-input v-model="searchFrom.title" placeholder="请输入标题" />
      <el-button type="primary" @click="findData()">
        <el-icon>
          <Search />
        </el-icon>
        查询
      </el-button>
      <el-button type="danger" @click="reset()">
        <el-icon>
          <Refresh />
        </el-icon>
        重置
      </el-button>
    </div>

  </el-card>

  <el-card>
    <div>
      <el-button key="'添加资讯'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
        class="addUser">添加资讯</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="author" label="作者" width="80" />
      <el-table-column prop="publishTime" label="发布时间" width="200" />
      <el-table-column fixed="right" label="操作" width="280">
        <template #default="scope">
          <el-space wrap>
            <el-button type="primary" size="small" plain @click="findRoleInfo(scope.row.id)">查看</el-button>
            <el-button v-if="infoStore.$state.info.role == 'admin'" type="primary" size="small" plain
              @click="editRoleInfo(scope.row.id)">编辑</el-button>
            <el-button v-if="infoStore.$state.info.role == 'admin'" type="danger" size="small" color="red" plain
              @click="deleteRoleInfo(scope.row.id)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>

    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-card>
  <!-- 添加户主弹框 -->
  <el-dialog v-model="dialogHost" :title="dialogHostTitle">
    <el-form :model="addHsotForm">
      <el-form-item label="标题:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.title" autocomplete="off" placeholder="请输入标题" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="作者:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.author" autocomplete="off" placeholder="请输入作者" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="资讯内容:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.content" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入内容"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="图片:" :label-width="formLabelWidth" clearable :disabled="!isReadonlyHandler">
        <el-upload v-model:file-list="fileList" :http-request="updataImg" v-if="isReadonlyHandler"
          :headers="{ 'Content-Type': 'multipart/form-data' }" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :disabled="!isReadonlyHandler">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <div v-else v-for="fit in fileList" :key="fit" class="block" style="display: flex;flex-wrap: wrap;margin: 8px;">
          <el-image style="width: 250px; height: 250px" :src="fit.url" :fit="'contain'">
            <template #error>
              <div style="width: 100%;height: 100%;display: flex;align-items: center;">
                无图片
              </div>
            </template></el-image>
        </div>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogHost = false">取消</el-button>
        <el-button v-if="isReadonlyHandler" type="primary" @click="addHostSubmit()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input {
  margin-right: 5px;
  width: 400px;
}

.query-input {
  display: flex;
  gap: 10;
}

.el-card {
  margin-bottom: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.addUser {
  float: right;
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
  width: 400px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>